import React, { useState, useEffect } from 'react';
import { Form, Select, Button, Space, message, DatePicker } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import { createBooking } from '../../store/slices/bookingSlice';
import { fetchFlights } from '../../store/slices/flightSlice';
import { fetchPassengers } from '../../store/slices/passengerSlice';

const { Option } = Select;

const BookingForm = ({ onCancel, onSuccess }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();
  
  const { flights } = useSelector((state) => state.flights);
  const { passengers } = useSelector((state) => state.passengers);

  useEffect(() => {
    dispatch(fetchFlights());
    dispatch(fetchPassengers());
  }, [dispatch]);

  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      // 获取选中的航班信息来计算价格
      const selectedFlight = flights.find(f => f.id === values.flight_id);
      const price = selectedFlight ? selectedFlight.price : 1000;
      
      const bookingData = {
        passenger_id: values.passenger_id,
        flight_id: values.flight_id,
        seat_number: values.seat_number || null,
        price: price
      };
      
      await dispatch(createBooking(bookingData));
      message.success('预订创建成功');
      onSuccess();
      form.resetFields();
    } catch (error) {
      message.error('预订创建失败');
    } finally {
      setLoading(false);
    }
  };

  const availableFlights = flights.filter(flight => 
    new Date(flight.departure_time) > new Date() && 
    flight.available_seats > 0
  );

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
    >
      <Form.Item
        label="选择航班"
        name="flight_id"
        rules={[{ required: true, message: '请选择航班' }]}
      >
        <Select placeholder="选择航班" showSearch optionFilterProp="children">
          {availableFlights.map(flight => (
            <Option key={flight.id} value={flight.id}>
              {`${flight.flight_number} - ${flight.origin} → ${flight.destination} (${new Date(flight.departure_time).toLocaleDateString()})`}
            </Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item
        label="选择乘客"
        name="passenger_id"
        rules={[{ required: true, message: '请选择乘客' }]}
      >
        <Select placeholder="选择乘客" showSearch optionFilterProp="children">
          {passengers.map(passenger => (
            <Option key={passenger.id} value={passenger.id}>
              {passenger.name} ({passenger.email})
            </Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item
        label="座位号"
        name="seat_number"
        rules={[{ max: 10, message: '座位号不能超过10个字符' }]}
      >
        <Input placeholder="例如：12A" />
      </Form.Item>

      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit" loading={loading}>
            创建预订
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default BookingForm;